package log

import (
	"awesomeTask/application/variable"
	"awesomeTask/system/echo"
	"awesomeTask/system/event"
	"awesomeTask/system/helper"
	"fmt"
	"os"
	"time"
)

var Level map[string]string = map[string]string{
	"WARNING": "WARNING",
	"ALL":     "ALL",
	"TRACE":   "TRACE",
	"DEBUG":   "DEBUG",
	"INFO":    "INFO",
	"WARN":    "WARN",
	"ERROR":   "ERROR",
	"FATAL":   "FATAL",
	"OFF":     "OFF",
}

type FileLoger struct {
	LogPath string
}

func appendToFile(file, str string) {
	f, err := os.OpenFile(file, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
	if err != nil {
		fmt.Printf("Cannot open file %s!\n", file)
		return
	}
	defer f.Close()
	f.WriteString(str)
}
func (loger FileLoger) writeLog(level string, message string) {
	logMessage := helper.Format("[{}]--[{}]--[{}]", level, time.Now().Format("2006-01-02 15:04:05"), message) + "\n"
	helper.AppendFile(loger.LogPath+time.Now().Format("2006-01-02")+".log", logMessage)
	switch level {
	case "WARN":
		echo.Yellow(logMessage)
		break
	case "ERROR":
		echo.Red(logMessage)
		break
	case "Fatal":
		echo.Red(logMessage)
		break
	case "OFF":
		echo.Red(logMessage)
		break
	default:
		echo.Blue(logMessage)
		break
	}
	event.Dispatch(variable.ON_LOG, message)
}
func (loger FileLoger) All(message string) {
	loger.writeLog("ALL", message)
}
func (loger FileLoger) Trace(message string) {
	loger.writeLog("TRACE", message)
}
func (loger FileLoger) Debug(message string) {
	loger.writeLog("DEBUG", message)
}
func (loger FileLoger) Info(message string) {
	loger.writeLog("INFO", message)
}
func (loger FileLoger) Warn(message string) {
	loger.writeLog("WARN", message)
}
func (loger FileLoger) Error(message string) {
	loger.writeLog("ERROR", message)
}
func (loger FileLoger) Fatal(message string) {
	loger.writeLog("FATAL", message)
}
func (loger FileLoger) Off(message string) {
	loger.writeLog("OFF", message)
}
